<template>
  <div class="app-container">
    <div class="title">
      <div class="title-name">{{$route.meta.title}}</div>
      <div class="title-icon">
        <i class="iconfont iconhelp" @click="preview"></i>
      </div>
    </div>
    <div class="tatletitle">
      <el-row :gutter="20">
        <!--业务类别数据-->
        <el-col :span="5" :xs="24">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              ref="tree"
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="childrenNum">{{ data.childrenNum }}</span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="19" :xs="24">
          <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="业务手册名称" prop="title">
              <el-input
                v-model="queryParams.title"
                placeholder="请输入"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="更新时间" prop="fileUpdateTime">
              <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['library:guide:add']"
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['library:guide:remove']"
                type="primary"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
              >删除</el-button>
            </el-col>
          </el-row>
          <el-table
            stripe
            v-loading="loading"
            :data="dataList"
            @selection-change="handleSelectionChange"
            @sort-change="tableSortChange"
            :default-sort="{prop: 'fileUpdateTime', order: 'descending'}"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="业务手册名称"
              align="center"
              prop="title"
              :sort-orders="['ascending', 'descending']"
              sortable="custom"
            />
            <el-table-column
              label="业务类别"
              align="center"
              prop="businessName"
              :sort-orders="['ascending', 'descending']"
              sortable="custom"
            />
            <el-table-column
              label="更新时间"
              align="center"
              prop="fileUpdateTime"
              :sort-orders="['ascending', 'descending']"
              sortable="custom"
            >
              <template slot-scope="scope">{{ parseTime(scope.row.fileUpdateTime) }}</template>
            </el-table-column>
            <el-table-column
              label="业务手册文件"
              align="left"
              prop="fileName"
              :show-overflow-tooltip="true"
              :sort-orders="['ascending', 'descending']"
              sortable="custom"
            />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  icon="el-icon-search"
                  type="text"
                  @click="handlePreview(scope.row)"
                >预览</el-button>
                <el-button
                  v-hasPermi="['library:guide:edit']"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                >编辑</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>

      <!-- 添加或修改归档模板对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="50%">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="业务手册名称" prop="title">
            <el-input v-model="form.title" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="业务类别" prop="businessCategoryId">
            <treeselect
              v-model="form.businessCategoryId"
              :options="deptOptions"
              placeholder="请选择业务类别"
              :disable-branch-nodes="true"
            />
          </el-form-item>
          <el-form-item label="附件" prop="contentGuid">
            <vue-uploader
              v-if="open"
              :single-type="true"
              :file-list="attachments"
              @changeFileData="changeFile"
              @removeFileList="removeFileList"
              :pathName="'TJECdocuments/业务标准库/业务手册'"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="备注" type="textarea" :rows="2" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 预览 -->
      <el-dialog :title="title" :visible.sync="openPreview" width="80%">
        <iframe :src="manualPreviewUrl" frameborder="0" width="100%" height="700px"></iframe>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  libraryTree,
  guideSelectList,
  addLibrary,
  deLlibrary,
  getGuideDetail,
  updatelibrary
} from "@/api/library/manual.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import vueUploader from "@/components/Uploader";
export default {
  name: "Manual",
  components: {
    Treeselect,
    vueUploader
  },
  data () {
    return {
      manualPreviewUrl: null,
      openPreview: false,
      taskSingle: false,
      // 遮罩层
      loading: false,
      // 选中数组
      guids: [],
      titles: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      dateRange: [],
      attachments: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessCategoryId: undefined,
        title: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "业务手册名称不能为空", trigger: "blur" }
        ],
        contentGuid: [
          { required: true, message: '附件不能为空', trigger: 'blur' }
        ],
        businessCategoryId: [
          { required: true, message: "业务类别不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.titles = selection.map(item => item.title);
      this.guids = selection.map(item => item.guid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    resetQuery () {
      this.queryParams.title = undefined;
      this.dateRange = [];
      this.queryParams.pageNum = 1;
      this.queryParams.businessCategoryId = undefined;
      this.getList();
    },
    // 表单重置
    reset () {
      this.attachments = [];
      this.form = {
        guid: undefined,
        businessCategoryId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加业务手册";
    },
    handlePreview (row) {
      this.filePreview(row.fileName, row.storagePath);
    },
    preview () {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}业务标准库/业务手册.xlsx`
      )}&name=${encodeURIComponent("业务手册.xlsx")}`;
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const guid = row.guid || this.guids;
      getGuideDetail(guid).then(response => {
        this.form = response.data;
        this.attachments.push({
          fileName: response.data.fileName,
          storagePath: response.data.storagePath,
          guid: response.data.guid
        });
        this.open = true;
        this.title = "修改业务手册";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.guid != undefined) {
            updatelibrary(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.getTreeselect();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addLibrary(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.getTreeselect();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.guid || this.guids;
      const titles = row.title || this.titles;
      this.$confirm(
        '是否确认删除业务手册名称为' + titles + '的文件?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function () {
          return deLlibrary(ids);
        })
        .then(() => {
          this.getList();
          this.getTreeselect();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
    /** 查询归档模板列表 */
    getList () {
      this.loading = true;
      guideSelectList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect () {
      libraryTree("OPERATIONS_MANUAL").then(response => {
        this.deptOptions = JSON.parse(
          JSON.stringify(response.data).replace(/isDisabled/g, "checkbox")
        );
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      if (data.label != null) {
        return data.label.indexOf(value) !== -1;
      }
    },
    // 节点单击事件
    handleNodeClick (data) {
      this.queryParams.businessCategoryId = data.id;
      this.getList();
    },
    // 附件操作
    changeFile (id, name) {
      this.form.contentGuid = id;
      this.attachments = [];
      // this.attachments = [{ fileName: name, guid: id }]
    },
    removeFileList (id) {
      this.form.contentGuid = null;
      this.attachments = [];
    },
    tableSortChange (column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.tatletitle {
  margin: 0 20px;
}
.title {
  height: 30px;
  width: 100%;
  display: flex;
  // align-items: center;
  border-bottom: 1px solid #dfe6ec;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 20px;
  .title-name {
    width: 200px;
  }
  .title-icon {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    cursor: pointer;
    .iconhelp {
      font-size: 18px;
    }
  }
}
</style>
